package com.example.behaviour.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.apis.article.iArticleClient;
import com.example.behaviour.mapper.ApCommentThumbMapper;
import com.example.behaviour.mapper.ApUserMsgMapper;
import com.example.behaviour.mapper.ApUserScoreMapper;
import com.example.behaviour.pojos.*;
import com.example.behaviour.repository.CommentRepository;
import com.example.behaviour.service.CommentService;
import com.example.model.article.pojos.ApArticle;
import com.example.model.article.pojos.ApUserScore;
import com.example.model.common.dtos.ResponseResult;
import com.example.model.user.pojos.ApUser;
import com.example.user.mapper.ApUserMapper;
import io.goeasy.GoEasy;
import io.goeasy.publish.GoEasyError;
import io.goeasy.publish.PublishListener;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private iArticleClient iArticleClient;

    @Autowired
    private ApCommentThumbMapper apCommentThumbMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private ApUserMapper apUserMapper;

    @Autowired
    private ApUserScoreMapper apUserScoreMapper;

    @Override
    public ResponseResult saveComment(Comment comment,ApUser apUser) {
//        commentRepository.save(comment);
        mongoTemplate.insert(comment,"comment");

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",apUser.getId());
        queryWrapper.eq("articleId",comment.getArticleId());
        ApUserScore apUserScore = apUserScoreMapper.selectOne(queryWrapper);
        if(apUserScore == null){
            ApUserScore apUserScore1 = new ApUserScore();
            apUserScore1.setScore(3.0);
            apUserScore1.setUserId(apUser.getId());
            apUserScore1.setArticleId(comment.getArticleId());
            apUserScoreMapper.insert(apUserScore1);
        }else{
            apUserScore.setScore(apUserScore.getScore()+3.0);
            apUserScoreMapper.updateById(apUserScore);
        }

        if(!"0".equals(comment.getParentId())){
            String parentId = comment.getParentId();
            Comment pComment = commentRepository.getCommentById(parentId);

            ApUserMsg apUserMsg = new ApUserMsg();
            apUserMsg.setFromUser(apUser.getName());
            apUserMsg.setFromId(apUser.getId());
            apUserMsg.setContent(apUserMsg.getFromUser()+"回复了您的评论");
            apUserMsg.setType(3);
            apUserMsg.setCreatedTime(new Date());
            apUserMsg.setUserId(Integer.parseInt(pComment.getUserId()));
            apUserMsg.setIsRead(0);
            apUserMsg.setArticleId(comment.getArticleId());
            apUserMsgMapper.insert(apUserMsg);

            ApUser toUser = apUserMapper.selectById(apUserMsg.getUserId());

            GoEasy goEasy = new GoEasy("https://rest-hz.goeasy.io", "BC-b6050660635342f89d6b38039bfa2af0");
            goEasy.publish(toUser.getName(), apUserMsg.getFromUser()+"回复了您的评论", new PublishListener(){
                @Override
                public void onSuccess() {
                    System.out.println("Publish success.");
                }

                @Override
                public void onFailed(GoEasyError error) {
                    System.out.println("Failed to Publish message, error:" + error.getCode() + " , " + error.getContent());
                }
            });
        }



        ResponseResult responseResult = iArticleClient.addCommentsNum(comment.getArticleId());
        System.out.println(responseResult.getData());
        return ResponseResult.okResult("发表评论成功");
    }

    @Override
    public ResponseResult findCommentsByUserId(Integer userId) {
        List<Comment> commentList = commentRepository.findByUserId(userId.toString());
        // 使用 Collections.sort() 方法对 comments 进行排序
        Collections.sort(commentList, new Comparator<Comment>() {
            @Override
            public int compare(Comment c1, Comment c2) {
                // 根据 createdTime 属性进行比较
                return c2.getCreatedTime().compareTo(c1.getCreatedTime());
            }
        });
        return ResponseResult.okResult(commentList);
    }

    @Override
    public ResponseResult findCommentsByArticleId(String articleId,String userId) {

        List<Comment> commentList = commentRepository.findByArticleId(articleId);
//        for (int i = 0;i < commentList.size();i++){
//            String parentId = commentList.get(i).getParentId();
//            if(!"0".equals(parentId)){
//                Comment comment = commentRepository.getCommentByParentId(parentId);
//                commentList.get(i).setToName(comment.getNickname());
//            }
//
//        }
        log.info("commentList {}", Arrays.toString(commentList.toArray()));

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        List<ApCommentThumb> list = apCommentThumbMapper.selectList(queryWrapper);

        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < commentList.size(); j++) {
                if(list.get(i).getCommentId().equals(commentList.get(j).getId())){
                    commentList.get(j).setLiked(true);
                }
            }
        }


        for (int i = 0; i < commentList.size(); i++) {
            ApUser apUser = apUserMapper.selectById(commentList.get(i).getUserId());
            commentList.get(i).setImage(apUser.getImage());
            List<Comment> comments = new ArrayList<>();
            commentList.get(i).setChildComment(comments);
        }
//        System.out.println("1 "+commentList);
        List<Comment> newCommonList = new ArrayList<>();
        for (int i = 0; i < commentList.size(); i++) {
            if("0".equals(commentList.get(i).getParentId())){
                newCommonList.add(commentList.get(i));
            }
        }

        for (int i = 0; i < commentList.size(); i++) {
            //System.out.println(commentList);
            for (int j = 0; j < newCommonList.size(); j++) {
                if(commentList.get(i).getParentId().equals(newCommonList.get(j).getId())){
                    newCommonList.get(j).getChildComment().add(commentList.get(i));
                    //commentList.remove(i);
                }
            }
            //System.out.println(commentList);
        }
//        System.out.println("2 "+commentList);
        return ResponseResult.okResult(newCommonList);
    }
    @Autowired
    private ApUserMsgMapper apUserMsgMapper;

    @Override
    public ResponseResult likeComment(String id, Integer userId) throws ParseException {
//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("commentId",id);
//        queryWrapper.eq("userId",userId);
//        ApCommentThumb apCommentThumb = apCommentThumbMapper.selectOne(queryWrapper);

//        Comment comment = commentRepository.getCommentById(id);

        CommentDto commentDto = mongoTemplate.findById(id,CommentDto.class);
        System.out.println(commentDto);
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

        Date date = dateFormat.parse(commentDto.getCreatedTime());


        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDto,comment);
        date.setTime(date.getTime() + (8 * 60 * 60 * 1000));
        comment.setCreatedTime(date);

        ApUser apUser = apUserMapper.selectById(userId);
        ApUserMsg apUserMsg = new ApUserMsg();
        apUserMsg.setFromUser(apUser.getName());
        apUserMsg.setCreatedTime(new Date());
        apUserMsg.setType(2);
        apUserMsg.setIsRead(0);
        apUserMsg.setFromId(userId);
        apUserMsg.setUserId(Integer.parseInt(comment.getUserId()));
        apUserMsg.setContent(apUserMsg.getFromUser()+"给您点赞了");
        apUserMsg.setArticleId(comment.getArticleId());
        apUserMsgMapper.insert(apUserMsg);

        ApUser toUser = apUserMapper.selectById(apUserMsg.getUserId());

        GoEasy goEasy = new GoEasy("https://rest-hz.goeasy.io", "BC-b6050660635342f89d6b38039bfa2af0");
        goEasy.publish(toUser.getName(), apUserMsg.getFromUser()+"给您点赞了", new PublishListener(){
            @Override
            public void onSuccess() {
                System.out.println("Publish success.");
            }

            @Override
            public void onFailed(GoEasyError error) {
                System.out.println("Failed to Publish message, error:" + error.getCode() + " , " + error.getContent());
            }
        });

        comment.setLikeNum(comment.getLikeNum()+1);
        commentRepository.save(comment);
        ApCommentThumb apCommentThumb1 = new ApCommentThumb();
        apCommentThumb1.setUserId(userId);
        apCommentThumb1.setCommentId(id);
        apCommentThumb1.setToId(comment.getUserId());
        apCommentThumbMapper.insert(apCommentThumb1);

        return ResponseResult.okResult("点赞成功");
    }

    @Override
    public ResponseResult unLikeComment(String id, Integer userId) throws ParseException {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        queryWrapper.eq("commentId",id);
        apCommentThumbMapper.delete(queryWrapper);

        CommentDto commentDto = mongoTemplate.findById(id,CommentDto.class);
        System.out.println(commentDto);
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

        Date date = dateFormat.parse(commentDto.getCreatedTime());


        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDto,comment);
        date.setTime(date.getTime() + (8 * 60 * 60 * 1000));
        comment.setCreatedTime(date);

        comment.setLikeNum(comment.getLikeNum()-1);
        commentRepository.save(comment);
        return ResponseResult.okResult("取消点赞成功");
    }

    @Override
    public ResponseResult getCommentNum(Integer userId) {
        List<Comment> commentList = commentRepository.getCommentByUserId(userId.toString());
        return ResponseResult.okResult(commentList.size());
    }

    @Override
    public ResponseResult getOtherCommentNum(String name) {
        List<Comment> commentList = commentRepository.getCommentByNickname(name);
        return ResponseResult.okResult(commentList.size());
    }

    @Override
    public ResponseResult delComment(String id) {
        CommentDto commentDto = mongoTemplate.findById(id,CommentDto.class);
        System.out.println(commentDto);
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

        Date date = null;
        try {
            date = dateFormat.parse(commentDto.getCreatedTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }


        Comment comment = new Comment();
        BeanUtils.copyProperties(commentDto,comment);
        date.setTime(date.getTime() + (8 * 60 * 60 * 1000));
        comment.setCreatedTime(date);
        comment.setContent("评论已删除");
        mongoTemplate.save(comment);
        return ResponseResult.okResult("评论删除成功");
    }


    @Override
    public ResponseResult getReplyData(Integer id) {
        List<Comment> commentByUserId = commentRepository.getCommentByUserId(id.toString());
        List<ApReplyDataDto> dataDtos = new ArrayList<>();
        for (Comment comment : commentByUserId) {
            if(!"0".equals(comment.getParentId())){
                ResponseResult article = iArticleClient.getArticleByArticleId(comment.getArticleId());
                JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(article.getData()));
                ApArticle apArticle = JSON.toJavaObject(jsonObject, ApArticle.class);

                ApReplyDataDto child = new ApReplyDataDto();
                child.setArticleId(comment.getArticleId());
                child.setContent(comment.getContent());
                child.setCreatedTime(comment.getCreatedTime());
                child.setUserId(comment.getUserId());
                ApUser apUser_child = apUserMapper.selectById(comment.getUserId());
                child.setNickname(comment.getNickname());
                child.setImage(apUser_child.getImage());
                child.setCover(apArticle.getImages());

                Comment pComment = commentRepository.getCommentById(comment.getParentId());
                ApReplyDataDto parent = new ApReplyDataDto();
                parent.setUserId(pComment.getUserId());
                ApUser apUser_parent = apUserMapper.selectById(pComment.getUserId());
                parent.setImage(apUser_parent.getImage());
                parent.setContent(pComment.getContent());
                parent.setCreatedTime(pComment.getCreatedTime());
                parent.setNickname(pComment.getNickname());
                parent.setArticleId(pComment.getArticleId());
                parent.setChild(child);
                parent.setCover(apArticle.getImages());
                parent.setArticleName(apArticle.getTitle());

                dataDtos.add(parent);
            }
        }
        return ResponseResult.okResult(dataDtos);
    }


}
